﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Web;

namespace IXION.BLOG.COMMON.DATA
{
    /// <summary>
    /// NHibernate 工具类
    /// </summary>
    public class NHibernateHelper
    {
        protected string NHIBERNATE_KEY = "NHIBERNATE";
        protected static object _lock = new object();
        protected static NHibernateHelper helper;
        private ISession session = null;
        private static ISessionFactory sFactory = null;
        private const string NHIBERNATE_CONFIG_FILE_PATH = @"App_Data\config\NHibernate.xml";
        private NHibernateHelper() {
            if (sFactory == null)
            {
                Configuration cfg = new Configuration().Configure(this.GetConfigFile());
                sFactory = cfg.BuildSessionFactory();
            }
        }

        private string GetConfigFile()
        {
            return System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, NHIBERNATE_CONFIG_FILE_PATH);
            //throw new NotImplementedException();
        }
        public static NHibernateHelper Instance
        {
            get
            {
                if (helper == null)
                {
                    lock (_lock)
                    {
                        if (helper == null)
                        {
                            helper = new NHibernateHelper();
                        }
                    }
                }
                return helper;
            }
        }
        public ISession GetSession()
        {
            if (HttpContext.Current == null)
            {
                return sFactory.OpenSession();
            }
            session = HttpContext.Current.Items[NHIBERNATE_KEY] as ISession;
            if (session == null)
            {
                session = sFactory.OpenSession();
                HttpContext.Current.Items[NHIBERNATE_KEY] = session;
            }
            return session;
        }
        public void CloseSession()
        {
            session = HttpContext.Current.Items[NHIBERNATE_KEY] as ISession;
            if (session != null)
            {
                session.Close();
                HttpContext.Current.Items[NHIBERNATE_KEY] = null;
            }
        }
    }
}